﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharepointSolutionInstaller.Views;
using Microsoft.SharePoint.Administration;
using SharepointSolutionInstaller.Resources;
using System.Threading;
using SharepointSolutionInstaller.Utils.Log;

namespace SharepointSolutionInstaller.Utils.SolutionDeployment
{
    public abstract class JobCommand : Command
    {
  
        protected JobCommand(InstallProcess parent) : base(parent) { }

        protected static void RemoveExistingJob(SPSolution solution)
        {
            if (solution.JobStatus == SPRunningJobStatus.Initialized)
            {
                throw new Exception(CommonUIStrings.installExceptionDuplicateJob);
            }
            SPJobDefinition jobDefinition = GetSolutionJob(solution);
            if (jobDefinition != null)
            {
                jobDefinition.Delete();
                Thread.Sleep(500);
            }
        }

        private static SPJobDefinition GetSolutionJob(SPSolution solution)
        {
            SPFarm localFarm = SPFarm.Local;
            SPTimerService service = localFarm.TimerService;
            foreach (SPJobDefinition definition in service.JobDefinitions)
            {
                if (definition.Title != null && definition.Title.Contains(solution.Name))
                {
                    return definition;
                }
            }
            return null;
        }

        protected static DateTime GetImmediateJobTime()
        {
            return DateTime.Now - TimeSpan.FromDays(1);
        }
    }
}
